package com.education.utils;

import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import com.education.common.utils.Convert;
import com.education.welco.mapper.CourseNoteMapper;
import com.education.welco.mapper.MineResTableMapper;
import com.education.welco.mapper.PlatformResourcesMapper;
import com.education.welco.mapper.SResourcesMapper;
import com.education.welco.pojo.CourseNote;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: liftsail
 * @Date: 2022/11/9 16:34
 * @Description: 不积跬步无以至千里
 */
@Slf4j
@Component
@EnableAsync
public class BaiduAipContentCensor {

    private static volatile AipContentCensor aipClient = null;

    //设置APPID/AK/SK
    public static final String APP_ID = "24664916";
    public static final String API_KEY = "gwHZaP09ZT2CUoYGGR0pZIBj";
    public static final String SECRET_KEY = "VWF9cqGGOUgPI85h87rAwKkoM4P06pt7";

    /**
     * 我的资源库mappr
     */
    @Autowired
    private MineResTableMapper mineResTableMapper;
    /**
     * 平台资源库mapper
     */
    @Autowired
    private PlatformResourcesMapper platformResourcesMapper;
    @Autowired
    private CourseNoteMapper courseNoteMapper;
    @Autowired
    private SResourcesMapper sResourcesMapper;

    /**
     * 目前按照两种思路
     * 1.批量图片
     * 2.单个视频
     */

    /**
     * @param contentUrl 资源url
     * @param tableName  表名
     * @param resType    图片1 视频2 文档3
     */
    @Async("taskExecutor")
    public void singleFileAddSave(String contentUrl, String tableName, String resType) {
        if ("1".equals(resType)) { //图片
            if (singleAipImage(contentUrl) == false) { //审核不通过-修改状态
                //资源不通过逻辑-2
                if (tableName.equals("mineResTable")) {
                    mineResTableMapper.updateMineResTableByUrl(contentUrl, "2");
                    //int i = mineResTableMapper.deleteMineResTableByUrl(contentUrl);
                } else if (tableName.equals("platform_resources")) {
                    int i = platformResourcesMapper.updatePlatformResourcesByUrl(contentUrl, "2");
                    //int i = platformResourcesMapper.deletePlatformResourcesByUrl(contentUrl);
                } else if (tableName.equals("s_resources")) {
                    int i = sResourcesMapper.updateSResourcesByUrl(contentUrl, "2");
                }
            } else if (singleAipImage(contentUrl) == true) { //审核通过-修改状态
                //资源状态修改逻辑-1
                if (tableName.equals("mineResTable")) {
                    mineResTableMapper.updateMineResTableByUrl(contentUrl, "1");
                } else if (tableName.equals("platform_resources")) {
                    int i = platformResourcesMapper.updatePlatformResourcesByUrl(contentUrl, "1");
                } else if (tableName.equals("s_resources")) {
                    int i = sResourcesMapper.updateSResourcesByUrl(contentUrl, "1");
                }
            }
        } else if ("2".equals(resType)) { //视频
            if (singleAipVideo(contentUrl) == false) { //审核不通过-修改状态-2
                //资源不通过逻辑-2
                if (tableName.equals("mineResTable")) {
                    mineResTableMapper.updateMineResTableByUrl(contentUrl, "2");
                    //int i = mineResTableMapper.deleteMineResTableByUrl(contentUrl);
                } else if (tableName.equals("platform_resources")) {
                    int i = platformResourcesMapper.updatePlatformResourcesByUrl(contentUrl, "2");
                } else if (tableName.equals("s_resources")) {
                    int i = sResourcesMapper.updateSResourcesByUrl(contentUrl, "2");
                }
            } else if (singleAipVideo(contentUrl) == true) { //审核不通过-修改状态-1
                //资源通过逻辑-1
                if (tableName.equals("mineResTable")) {
                    mineResTableMapper.updateMineResTableByUrl(contentUrl, "1");
                } else if (tableName.equals("platform_resources")) {
                    int i = platformResourcesMapper.updatePlatformResourcesByUrl(contentUrl, "1");
                } else if (tableName.equals("s_resources")) {
                    int i = sResourcesMapper.updateSResourcesByUrl(contentUrl, "1");
                }
            }
        } else {
            return;
        }
    }

    /**
     * 单个审核图片(默认调用这个方法)
     *
     * @param imageUrl 单图片url
     * @return
     */
    public Boolean singleAipImage(String imageUrl) {
        JSONObject jsonObject = AipImage(imageUrl);
        if (checkResult(jsonObject) == 2) {
            //不合规删除资源
            QiniuUtil.deleteFileFromQiniu(imageUrl);
            return false;
        }
        return true;
    }

    /**
     * 单个审核视频(默认调用这个方法)
     *
     * @param videoUrl 单视频url
     * @return
     */
    public Boolean singleAipVideo(String videoUrl) {
        JSONObject jsonObject = AipVideo(videoUrl);
        if (checkResult(jsonObject) == 2) {
            //不合规删除资源
            QiniuUtil.deleteFileFromQiniu(videoUrl);
            return false;
        }
        return true;
    }

    /**
     * 批量审核图片(默认调用这个方法)
     *
     * @param imageUrls url拼接字符串(,隔开)
     * @return
     */
    @Async("taskExecutor")
    public void batchAipImage(String imageUrls, String tableName, Integer id) {
        //log.info(Thread.currentThread().getName());
        //处理拼接的字符串
        List<String> urlStrings = Arrays.asList(Convert.toStrArray(";", imageUrls));

        //通过迭代器修改list
        Iterator<String> urliterator = urlStrings.iterator();
        while (urliterator.hasNext()) {
            String next = urliterator.next();
            JSONObject jsonObject = AipImage(next);
            if (checkResult(jsonObject) == 2) {
                //不合规替换|删除资源
                QiniuUtil.deleteFileFromQiniu(next);
                urliterator.remove();
            }
        }
        String imageUrlsAfter = Convert.strSplitJoint(urlStrings, ";");
        //比对是否发生变化,从而修改表数据
        if (!imageUrls.equals(imageUrlsAfter)) {
            batchAipImageUpdate(imageUrlsAfter, id, tableName);
        }
        return;
    }

    /**
     * 批量审核图片mapper层修改-结合表名-通过主键id
     *
     * @param imageUrlsAfter 修改后的结果url
     * @param id             表主键id
     * @param tableName      表名
     */
    public void batchAipImageUpdate(String imageUrlsAfter, Integer id, String tableName) {
        if (tableName.equals("course_note")) {
            CourseNote courseNote = new CourseNote();
            courseNote.setId(id);
            courseNote.setNoteImage(imageUrlsAfter);
            courseNoteMapper.updateCourseNote(courseNote);
        }
    }

    /**
     * 审核文本
     *
     * @param text
     * @return
     */
    public int AipText(String text) {
        AipContentCensor client = initAipContentCensor();
        //参数为文字string
        //text = "滚你妈";
        JSONObject response = client.textCensorUserDefined(text);
        return checkResult(response);
    }

    /**
     * 审核图片
     *
     * @param imageUrl
     * @return
     */
    public JSONObject AipImage(String imageUrl) {
        AipContentCensor client = initAipContentCensor();
        //参数为本地图片路径
        /*String path = "test.jpg";
        JSONObject response = client.imageCensorUserDefined(path, EImgType.FILE, null);
        System.out.println(response.toString());*/

        //参数为url
        imageUrl = "http://jinruanresource.shixuncloud.com/" + imageUrl;
        JSONObject response = client.imageCensorUserDefined(imageUrl, EImgType.URL, null);
        //System.out.println(response.toString())

        //参数为本地图片文件二进制数组
        /*byte[] file = new byte[10] ;
        //= readImageFile(path);
        response = client.imageCensorUserDefined(file, null);
        System.out.println(response.toString());*/
        return response;
    }

    /**
     * 审核视频
     *
     * @param videoUrl
     * @return
     */
    public JSONObject AipVideo(String videoUrl) {
        AipContentCensor client = initAipContentCensor();
        //可选参数
        HashMap<String, String> options = new HashMap();
        //options.put("test", "http://114.115.233.40:8081/WebLoad/test.mp4");
        //options.put("extInfo", "[{\"subject\":\"账户信息\",\"fields\":[{\"title\":\"昵称\",\"value\":\"陈翔六点半\"}]}]");
        //视频url 地址
        //String videoUrl = "http://jinruanresource.shixuncloud.com/1202211091056181057539684.mp4";
        videoUrl = "http://jinruanresource.shixuncloud.com/" + videoUrl;
        //视频名字
        String name = videoUrl;
        //视频id;
        String extId = videoUrl;
        //设置链接超时时间
        client.setConnectionTimeoutInMillis(100000);
        client.setSocketTimeoutInMillis(200000);
        JSONObject jsonObject = client.videoCensorUserDefined(name, videoUrl, extId, null);
        return jsonObject;
    }

    /**
     * 单个视频审核2测试
     *
     * @param videoUrl
     * @return
     */
    public boolean AipVideo2(String videoUrl) {
        AipContentCensor client = initAipContentCensor();
        //可选参数
        HashMap<String, String> options = new HashMap();
        options.put("test", "http://114.115.233.40:8081/WebLoad/test.mp4");
        options.put("extInfo", "[{\"subject\":\"账户信息\",\"fields\":[{\"title\":\"昵称\",\"value\":\"陈翔六点半\"}]}]");
        //视频url 地址
        //String videoUrl = "http://jinruanresource.shixuncloud.com/1202211091056181057539684.mp4";
        videoUrl = "http://jinruanresource.shixuncloud.com/" + videoUrl;
        //视频名字
        String name = videoUrl;
        //视频id;
        String extId = "video001";
        //设置链接超时时间
        client.setConnectionTimeoutInMillis(10000);
        client.setSocketTimeoutInMillis(20000);
        JSONObject jsonObject = client.videoCensorUserDefined(name, videoUrl, extId, null);

        if (checkResult(jsonObject) == 2) {
            //不合规删除资源
            QiniuUtil.deleteFileFromQiniu(videoUrl);
            return false;
        }
        return true;
    }

    /**
     * 初始化aipClient管理器
     *
     * @return
     */
    private static AipContentCensor initAipContentCensor() {
        if (aipClient == null) {
            synchronized (AipContentCensor.class) {
                if (aipClient == null) {
                    aipClient = new AipContentCensor(APP_ID, API_KEY, SECRET_KEY);
                }
            }
        }
        return aipClient;
    }

    /**
     * 结论判断处理
     *
     * @param jsonObject
     * @return
     */
    public int checkResult(JSONObject jsonObject) {
        try {
            int conclusionType = jsonObject.getInt("conclusionType");
            return conclusionType;
        } catch (JSONException e) {
            e.printStackTrace();
            return -1;
        }
    }
}
